import { ElLoading, ElMessage } from "element-plus";
import Recorder from "recorder-core";

//需要使用到的音频格式编码引擎的js文件统统加载进来
import "recorder-core/src/engine/wav";
import Assert from "./Assert";
import HttpReqApi from "./http/HttpReqApi";
import MittUnit, { MittEvent } from "./MittUnit";
import VoiceRecordUnit from "./VoiceRecordUnit";
// import "recorder-core/src/engine/mp3";
// import "recorder-core/src/engine/mp3-engine";
export default class VoiceUnit {
    private static rec: any;

    private static recordTime:any = -1;


    private static loading:any = null;

    private static data:any = null;

    constructor() {
    }
    public static start(data:any,warnContent:string) {
        this.clearCheck();
        if (this.rec != null){
            Assert.isFalse(true,"当前有录音进行中")
        }
        
        this.data = data;

        this.rec = Recorder({
            type: "wav",
            sampleRate: 16000,
            bitRate: 16, //mp3格式，指定采样率hz、比特率kbps，其他参数使用默认配置；注意：是数字的参数必须提供数字，不要用字符串；需要使用的type类型，需提前把格式支持文件加载进来，比如使用wav格式需要提前加载wav.js编码引擎
        });
        this.rec.open(() => {
            console.log('开始录音');
            try {
                this.rec.start();
                VoiceRecordUnit.speak(warnContent);
                this.checkRecoder();
            } catch (error) {
                ElMessage.error(error+"");
                return;
            }
            this.loading = ElLoading.service({
                lock: true,
                text: '录音中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });
        }, (msg: any, isUserNotAllow: any) => {
            // This.dialogCancel();
            this.rec = null;
            
            let info =
                (isUserNotAllow ? "UserNotAllow，" : "") + "无法录音:" + msg;
                
            if(this.loading)
            this.loading.close();
            this.loading = null;
            ElMessage.error(msg);
            Assert.isFalse(true,info);
        });
        
    }

    private static checkRecoder(){
        this.recordTime = setInterval(()=>{
            if(VoiceRecordUnit.isRecording == false)
            {
                this.close();
            }
        },200);
    }

    //结束录音的方法
    private static close() {
        this.clearCheck();
        if (this.rec == null){
            Assert.isFalse(true,"当前没有录音进行中")
        }
        if(this.loading)
        this.loading.close();
        this.loading = null;

        let rec = this.rec;
        this.rec = null;
        if (!rec) {
            console.log("未打开录音");
            return;
        }

        rec.stop(async (blob: any, duration: any) => {
            rec.close();
            console.log("blob = ", blob);
            console.log((window.URL || webkitURL).createObjectURL(blob), "时长:" + duration + "ms");
            //已经拿到blob文件对象想干嘛就干嘛：立即播放、上传

            // /*立即播放例子*/
            // var audio=document.createElement("audio");
            // audio.controls=true;
            // document.body.appendChild(audio);
            // //简单的一哔，注意不用了时需要revokeObjectURL，否则霸占内存
            // audio.src=(window.URL||webkitURL).createObjectURL(blob);
            // audio.play();
            let fileName = new Date().getTime();

            let file = new window.File(
                [blob],
                fileName + ".wav",
                { type: "audio/wav" }
            );
            const form = new FormData();
            form.append("file", file);
            let res = await HttpReqApi.upload(form);
            if(res == "success")
            {
                let sendData = {...this.data,voiceName:fileName,type:[...this.data.type]};
                await HttpReqApi.updateEquip(sendData);
                MittUnit.emit(MittEvent.updateEquipSuccess);
                return;
            }
            Assert.isFalse(true,res+"");

            // var reader:any = new FileReader();
            // reader.addEventListener("load", ()=> {
            //     console.log(reader)
            //     if (reader.result.length > 100) {
            //     }
            // }, false);
            // reader.readAsDataURL(blob);
            // console.log(blob,duration,'blob')
            // let blobURL = window.URL.createObjectURL(blob)
            // console.log(blobURL,'--------')

            // uni.uploadFile({
            //     file: blob,
            //     name: 'file',
            //     formData:{
            //         file:blob
            //     },
            //     url:'https:xxxxxxxx/api/Upload/Upload',//上传录音的接口
            //     success: function(res:any) {
            //         log
            //     },
            //     fail(e:any) {
            //         console.log(e,'失败原因')

            //     },
            //     complete() {

            //     }
            // })
        }, (s: any) => {
            rec.close();
            console.log("结束出错：" + s);
        }, true); //自动close
    }
    private static clearCheck(){
        if(this.recordTime == -1)return;
        clearInterval(this.recordTime);
    }

    public static async updateEquip(data:any){
        this.data = data;
        let sendData = {...this.data,voiceName:"",type:[...this.data.type]};
        await HttpReqApi.updateEquip(sendData);
        MittUnit.emit(MittEvent.updateEquipSuccess);
    }


}